package com.itheima.reggie.utils;

import com.itheima.reggie.config.MinioConfig;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class FileUploader {

    @Autowired
    MinioConfig minioConfig;

    public  String upload(MultipartFile file)  throws IOException, NoSuchAlgorithmException, InvalidKeyException {
        String fileName = null;
        try {
            String bucketName = minioConfig.getBucketName();
            //创建Minio的连接对象
            MinioClient minioClient = getClient();

            // 检查存储桶是否已经存在
            boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (isExist) {
                System.out.println("Bucket already exists.");
            } else {
                // 创建一个名为 reggie 的存储桶，用于存储照片的zip文件。
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }

            fileName = file.getOriginalFilename();//合同.pdf
            String objectName = UUID.randomUUID().toString().replaceAll("-", "")
                    + fileName.substring(fileName.lastIndexOf("."));

            // 使用putObject上传一个文件到存储桶中。
            PutObjectArgs objectArgs = PutObjectArgs.builder().object(objectName)
                    .bucket(bucketName)
                    .contentType(file.getContentType()) //image/jpeg    /text/html
                    .stream(file.getInputStream(),file.getSize(),-1).build();
            minioClient.putObject(objectArgs);

            // 返回上传成功对象  AjaxResult
        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
            System.out.println("HTTP trace: " + e.httpTrace());
        }
        return fileName;
    }

    /**
     * 免费提供一个获取Minio连接的方法
     * 获取Minio连接
     * @return
     */
    public MinioClient getClient(){
        MinioClient minioClient =
                MinioClient.builder()
                        // 设置连接哪个monio服务器
                        .endpoint("http://"+minioConfig.getEndpoint()+":"+ minioConfig.getPort())
                        .credentials(minioConfig.getAccessKey(),minioConfig.getSecretKey())
                        .build();
        return minioClient;
    }

    public void download(String name, HttpServletResponse res){

        /*try {

            String url = null;

            url = getClient().getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs.builder()
                            .method(Method.GET)
                            .bucket(minioConfig.getBucketName())
                            .object(name)
                            .expiry(2, TimeUnit.HOURS)
                            .build());

            //miniUtil.downloadFile(bucketName, fileName, "clues.xlsx", response);
            //获取文件数据对象

            StatObjectResponse statObjectResponse =
                    getClient().statObject(StatObjectArgs.builder().bucket(minioConfig.getBucketName()).object(name).build());
//			//以流的形式获取一个文件对象
            InputStream stream = null;
            if (statObjectResponse != null && statObjectResponse.size() > 0) {
                stream = getClient().getObject(
                        GetObjectArgs.builder()
                                .bucket(minioConfig.getBucketName())
                                .object(name)
                                .build());
            }
            String filename = new String(name.getBytes("ISO8859-1"), StandardCharsets.UTF_8);
            if (StringUtils.isNotEmpty("clues.xlsx")) {
                name = "clues.xlsx";
            }
            res.setHeader("Content-Disposition", "attachment;filename=" + filename);
            ServletOutputStream servletOutputStream = res.getOutputStream();
            int len;
            byte[] buffer = new byte[1024];
            while ((len = stream.read(buffer)) > 0) {
                servletOutputStream.write(buffer, 0, len);
            }
            servletOutputStream.flush();
            stream.close();
            servletOutputStream.close();
        }catch (Exception e) {
            // return AjaxResult.error(e.getMessage());
            e.printStackTrace();
        }*/




        try {
            String bucketName = minioConfig.getBucketName();
            MinioClient minioClient = getClient();
            InputStream stream; //= minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(minioConfig.getPort() + name).build());
            /*StatObjectResponse statObjectResponse =
                    getClient().statObject(StatObjectArgs.builder().bucket(minioConfig.getBucketName()).object(name).build());*/
            //InputStream inputStream = fileUploader.download(name,response);
            stream = getClient().getObject(GetObjectArgs.builder().bucket(minioConfig.getBucketName()).object(name).build());

            ServletOutputStream outputStream = res.getOutputStream();

            res.setContentType("image/jpeg");

            IOUtils.copy(stream,outputStream);//将输入流中的数据，拷贝到输出流中

            stream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }



        /*GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(minioConfig.getBucketName())
                .object(name).build();
        try (GetObjectResponse response = getClient().getObject(objectArgs)){
            byte[] buf = new byte[1024];
            int len;
            try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()){
                while ((len=response.read(buf))!=-1){
                    os.write(buf,0,len);
                }
                os.flush();
                byte[] bytes = os.toByteArray();
                res.setCharacterEncoding("utf-8");
                //设置强制下载不打开
                res.setContentType("application/force-download");
                res.addHeader("Content-Disposition", "attachment;fileName=" + name);
                try (ServletOutputStream stream = res.getOutputStream()){
                    stream.write(bytes);
                    stream.flush();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }*/


    }
}